package com.example.sprintboot.common;

import com.example.sprintboot.dto.WeChatAccessTokenResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信API工具类
 * 封装微信相关的网络请求操作
 */
@Component
public class WeChatApiUtil {

    @Autowired
    private HttpUtil httpUtil;

    /**
     * 微信API基础URL
     */
    private static final String WECHAT_API_BASE_URL = "https://api.weixin.qq.com";

    /**
     * 获取微信Access Token
     * 
     * @param appid 微信AppID
     * @param secret 微信AppSecret
     * @return Access Token响应结果
     */
    public WeChatAccessTokenResponse getAccessToken(String appid, String secret) {
        String url = WECHAT_API_BASE_URL + "/cgi-bin/token";
        
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", "client_credential");
        params.put("appid", appid);
        params.put("secret", secret);

        HttpUtil.HttpResult<WeChatAccessTokenResponse> result = httpUtil.get(
                url, params, WeChatAccessTokenResponse.class
        );

        if (result.isSuccess()) {
            return result.getData();
        } else {
            // 返回错误响应
            WeChatAccessTokenResponse errorResponse = new WeChatAccessTokenResponse();
            errorResponse.setErrcode(result.getStatusCode());
            errorResponse.setErrmsg(result.getErrorMessage());
            return errorResponse;
        }
    }

    /**
     * 发送微信订阅消息
     * 
     * @param accessToken 访问令牌
     * @param templateId 模板ID
     * @param touser 接收者openid
     * @param data 模板数据
     * @param miniprogramState 小程序状态
     * @return 发送结果
     */
    public WeChatSendMessageResponse sendSubscribeMessage(String accessToken, String templateId, 
                                                         String touser, Object data, String miniprogramState) {
        String url = WECHAT_API_BASE_URL + "/cgi-bin/message/subscribe/send";
        
        Map<String, Object> params = new HashMap<>();
        params.put("access_token", accessToken);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("template_id", templateId);
        requestBody.put("touser", touser);
        requestBody.put("data", data);
        if (miniprogramState != null) {
            requestBody.put("miniprogram_state", miniprogramState);
            requestBody.put("lang", "zh_CN");
        }

        // 打印详细的调试信息
        System.out.println("=== 微信订阅消息调试信息 ===");
        System.out.println("URL: " + url);
        System.out.println("Access Token: " + (accessToken != null ? accessToken.substring(0, Math.min(20, accessToken.length())) + "..." : "null"));
        System.out.println("Template ID: " + templateId);
        System.out.println("To User: " + touser);
        System.out.println("Miniprogram State: " + miniprogramState);
        System.out.println("Data: " + data);
        System.out.println("========================");

        HttpUtil.HttpResult<String> result = httpUtil.post(
                url, params, requestBody, String.class
        );

        WeChatSendMessageResponse response = new WeChatSendMessageResponse();
        response.setRawResponse(result.getRawResponse());

        // 无论HTTP状态码是什么，都要检查响应内容
        if (result.isSuccess()) {
            // HTTP 200 成功，解析微信API的响应
            try {
                if (result.getRawResponse() != null && !result.getRawResponse().trim().isEmpty()) {
                    // 解析JSON响应
                    com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                    @SuppressWarnings("unchecked")
                    java.util.Map<String, Object> responseMap = mapper.readValue(result.getRawResponse(), java.util.Map.class);
                    
                    if (responseMap.containsKey("errcode")) {
                        Integer errcode = (Integer) responseMap.get("errcode");
                        String errmsg = (String) responseMap.get("errmsg");
                        String msgid = (String) responseMap.get("msgid");
                        
                        response.setErrcode(errcode);
                        response.setErrmsg(errmsg);
                        response.setMsgid(msgid);
                        
                        System.out.println("=== 微信API响应解析 ===");
                        System.out.println("errcode: " + errcode);
                        System.out.println("errmsg: " + errmsg);
                        System.out.println("msgid: " + msgid);
                        System.out.println("====================");
                    } else {
                        // 没有errcode字段，可能是成功响应
                        response.setErrcode(0);
                        response.setErrmsg("ok");
                    }
                } else {
                    // 响应体为空，认为是成功
                    response.setErrcode(0);
                    response.setErrmsg("ok");
                }
            } catch (Exception e) {
                System.err.println("解析微信API响应失败: " + e.getMessage());
                response.setErrcode(-1);
                response.setErrmsg("响应解析失败: " + e.getMessage());
            }
        } else {
            // HTTP错误（如412）
            response.setErrcode(result.getStatusCode());
            response.setErrmsg("HTTP错误: " + result.getErrorMessage());
            
            System.out.println("=== HTTP错误详情 ===");
            System.out.println("状态码: " + result.getStatusCode());
            System.out.println("错误信息: " + result.getErrorMessage());
            System.out.println("响应体: " + result.getRawResponse());
            System.out.println("==================");
            
            // 特殊处理412错误
            if (result.getStatusCode() == 412) {
                response.setErrmsg("412 PRECONDITION_FAILED - 用户未订阅模板消息或订阅已过期");
            }
        }

        return response;
    }

    /**
     * 发送微信订阅消息（使用默认小程序状态）
     */
    public WeChatSendMessageResponse sendSubscribeMessage(String accessToken, String templateId, 
                                                         String touser, Object data) {
        return sendSubscribeMessage(accessToken, templateId, touser, data, "formal");
    }

    /**
     * 微信发送消息响应类
     */
    public static class WeChatSendMessageResponse {
        private Integer errcode;
        private String errmsg;
        private String msgid;
        private String rawResponse;

        public WeChatSendMessageResponse() {}

        public boolean isSuccess() {
            return errcode == null || errcode == 0;
        }

        // Getters and Setters
        public Integer getErrcode() { return errcode; }
        public void setErrcode(Integer errcode) { this.errcode = errcode; }

        public String getErrmsg() { return errmsg; }
        public void setErrmsg(String errmsg) { this.errmsg = errmsg; }

        public String getMsgid() { return msgid; }
        public void setMsgid(String msgid) { this.msgid = msgid; }

        public String getRawResponse() { return rawResponse; }
        public void setRawResponse(String rawResponse) { this.rawResponse = rawResponse; }
    }
}
